package com.example.util;

import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;

import cc.vv.lkbasecomponent.base.app.LKBaseApplication;

/**
 * @author: NPF
 * @date: 2018/4/10.
 */
public class ClipboardUtil {

    private static ClipboardUtil mInstance;

    private ClipboardUtil() {
    }

    public static ClipboardUtil getInstance() {
        if (null == mInstance) {
            synchronized (ClipboardUtil.class) {
                if (null == mInstance) {
                    mInstance = new ClipboardUtil();
                }
            }
        }
        return mInstance;
    }


    /**
     * 复制
     *
     * @param text
     */
    public void copy(String text) {
        ClipboardManager clipboard = (ClipboardManager) LKBaseApplication.getApplication().getSystemService(Context.CLIPBOARD_SERVICE);
        ClipData clipData = ClipData.newPlainText("label_text", text.trim());
        clipboard.setPrimaryClip(clipData);
    }

    /**
     * 获取粘贴板数据
     *
     * @return
     */
    public String paste() {
        ClipboardManager clipboard = (ClipboardManager) LKBaseApplication.getApplication().getSystemService(Context.CLIPBOARD_SERVICE);

        String clipText = "";
        if (!clipboard.hasPrimaryClip()) {
            return "";
        } else {
            ClipData clipData = clipboard.getPrimaryClip();
            int count = clipData.getItemCount();
            for (int i = 0; i < count; ++i) {
                ClipData.Item item = clipData.getItemAt(i);
                CharSequence str = item.coerceToText(LKBaseApplication.getApplication());
                clipText += str;
            }

            return clipText.trim();
        }
    }
}
